package com.lv.suyiyong.hfr.fragment

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.util.isNotEmpty
import androidx.core.util.size
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.imageview.ShapeableImageView
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.adapter.SubAdapter
import com.lv.common.base.BaseActivity
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.isJson
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.TimeUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.common.widget.linkbar.ZFlowLayout
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.common.widget.video.YGXVideoTopPlayer
import com.lv.service.adapter.RecyclerTextAdapter
import com.lv.service.bean.AddressDetailsBean
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.bean.LEDBeans
import com.lv.service.bean.ViewTypeBean
import com.lv.service.dialog.ListSingleTextTagPopupView
import com.lv.service.dialog.ShowCenterTextPopupView
import com.lv.service.dialog.ShowCodeBorderPopupView
import com.lv.service.event.TabPageEvent
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.CollectOrAttentionBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.company.CompanyItemBean
import com.lv.service.utils.UserUtils
import com.lv.service.weidget.picker.ListSingleTextPopupView
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.BannerMediaNoBroderAdapter
import com.lv.suyiyong.hfr.adapter.CompanyGoodsHorAdapter
import com.lv.suyiyong.hfr.adapter.CompanyHomeAddressAdapter
import com.lv.suyiyong.hfr.adapter.CompanyLedAdapter
import com.lv.suyiyong.hfr.adapter.CompanyRecomeGoodsAdapter
import com.lv.suyiyong.hfr.databinding.FragmentCompanyHomeBinding
import com.lv.suyiyong.hfr.ui.CompanyInfoActivity
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.enums.PopupPosition
import com.youth.banner.Banner
import com.youth.banner.listener.OnPageChangeListener
import com.youth.banner.transformer.ZoomOutPageTransformer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.math.abs

/**
 * 作者： ygx
 * 创建日期：2023/3/10 3:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述： NewTemplate 1 公司首页 黑色模板
 */
class CompanyHomeFragment : BaseFragment(), OnClickListener {

    private var mCpyid: String = ""
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val parmasMap = mutableMapOf<String, String>()
    private var mCompanyInfo: CompanyItemBean? = null
    private var mBannerAdapter: BannerMediaNoBroderAdapter? = null
    private var mBannerBeans = mutableListOf<ViewTypeBean>()
    private var inTentPosition = 0//跳转时轮播的位置
    private var inTentAction = false//跳转时轮播的位置
    private var mPhone = ""
    private var mGoodsUpAdapter: CompanyGoodsHorAdapter? = null
    private var mGoodsDownAdapter: CompanyGoodsHorAdapter? = null
    private var mRecomeGoodsAdapter: CompanyRecomeGoodsAdapter? = null
    private var mPhoneAdapter: RecyclerTextAdapter? = null
    private var mAddress: String = ""
    private var mIsFoucs = false//是否关注
    private val mViewList = mutableListOf<View>()
    private val mBnames = mutableListOf<String>()
    private val mAddressBeans = mutableListOf<CommonSelectedBean>()
    private val mGoodsUPBeans = mutableListOf<GoodsItemBean>()
    private val mGoodsDownBeans = mutableListOf<GoodsItemBean>()
    private val mGoodsRecomeBeans = mutableListOf<GoodsItemBean>()
    private var mAdapter: SubAdapter? = null
    private val mList = mutableListOf<String>()
    private var mUserInfo: UserInfo? = null
    private var mPhonesList = mutableListOf<CommonSelectedBean>()
    private val minLines = 3
    private var mLineCount = 0 //行数
    private var mTwoLineViewCount = 0 //前两行里面view的个数
    private var mExpandLineViewCount = 0

    //    private var mFacoryDatas = mutableListOf<ViewTypeBean>()
    private var mExpend: Boolean = false //是否展开
    private var mChangH = 100
    private var mShowCompanyDecPop = false
    private val serviceViewModel: ServiceViewModel by viewModel()
    private var mTvAttention: TextView? = null
    private var mTvXinyong: TextView? = null
    private var mTvCpname: TextView? = null


    private var mRvPhone: RecyclerView? = null
    private var mTvCompanyGoods: TextView? = null
    private var mTvProduct: TextView? = null
    private var mTvRecome: TextView? = null
    private var mBanner: Banner<*, *>? = null
    private var mBannerLed: Banner<*, *>? = null

    private var mIvTel: ImageView? = null
    private var mIvWeiChat: ImageView? = null
    private var mCpLogo: ShapeableImageView? = null

    private var mIvGold: ImageView? = null
    private var mTvGold: TextView? = null
    private var mRvUpGoods: RecyclerView? = null
    private var mRvDownGoods: RecyclerView? = null
    private var mRvRecomeGoods: RecyclerView? = null
    private var mRvAddress: RecyclerView? = null
    private var mCvCompanyGoods: ConstraintLayout? = null
    private var mCvRecome: ConstraintLayout? = null
    private var mFlowViewZ: ZFlowLayout? = null
    private var mViewHSub: View? = null
    private var mTvRZ: TextView? = null
    private var mIvGC: ImageView? = null
    private var mIvPP: ImageView? = null
    private var mViewLineGoods: View? = null
    private var mViewLineRecome: View? = null
    private var mAddressAdapter: CompanyHomeAddressAdapter? = null

    private var isLogin: Boolean = false
    private var mTxaccid = ""
    private var mSpecially = ""
    private var mCompanyCpName = ""
    private var mEwms = mutableListOf<String>()
    private var mSiteBeans = mutableListOf<AddressDetailsBean>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mBinding: FragmentCompanyHomeBinding? = null
    override fun getLayoutRes() = R.layout.fragment_company_home

    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentCompanyHomeBinding.bind(view).apply {
//            StatusBarUtil.setHeightAndPadding(requireContext(), viewSub)
//            StatusBarUtil.setHeightAndPadding(requireContext(), clContainer)
//            initSingleClickListener(ivBackWhite, ivBackWhite, ivShareWhite, ivShareBlack, llSearch)
        }
        return mBinding!!
    }


    override fun initConfig() {
        super.initConfig()
        mAddressBeans.clear()
        mAddressBeans.add(
            CommonSelectedBean(
                "腾讯地图",
                postiont = R.drawable.icon_map_tunxun
            )
        )
        mAddressBeans.add(
            CommonSelectedBean(
                "高德地图",
                postiont = R.drawable.icon_map_gaode
            )
        )
        mAddressBeans.add(
            CommonSelectedBean(
                "百度地图",
                postiont = R.drawable.icon_map_baidu
            )
        )

    }


    private fun initUI() {

        mAdapter = SubAdapter(mList)
        mBinding?.rvContent?.adapter = mAdapter
        val topHeader =
            layoutInflater.inflate(R.layout.fragment_company_home_header, null, false)
        mTvAttention = topHeader.findViewById(R.id.tv_attention)
        mCpLogo = topHeader.findViewById(R.id.iv_cp_logo)
        mIvGold = topHeader.findViewById(R.id.iv_gold)
        mTvGold = topHeader.findViewById(R.id.tv_gold)
//        mIvLocation = topHeader.findViewById(R.id.iv_location)
        mIvTel = topHeader.findViewById(R.id.iv_tel)
        mRvUpGoods = topHeader.findViewById(R.id.rv_up_goods)
        mRvDownGoods = topHeader.findViewById(R.id.rv_down_goods)
        mRvRecomeGoods = topHeader.findViewById(R.id.rv_recome_goods)
        mTvXinyong = topHeader.findViewById(R.id.tv_xinyong)
        mTvCpname = topHeader.findViewById(R.id.tv_cpname)

        mTvProduct = topHeader.findViewById(R.id.tv_produce)
        mTvRecome = topHeader.findViewById(R.id.tv_recome)
        mRvPhone = topHeader.findViewById(R.id.rv_phone)
        mRvAddress = topHeader.findViewById(R.id.rv_address)
        //        mTvContact2 = topHeader.findViewById(R.id.tv_contact_2)
//        mTvAddressDec = topHeader.findViewById(R.id.tv_address_dec)
        mTvCompanyGoods = topHeader.findViewById(R.id.tv_company_goods)
        mCvCompanyGoods = topHeader.findViewById(R.id.cv_company_goods)
        mCvRecome = topHeader.findViewById(R.id.cv_recome)
        mBanner = topHeader.findViewById(R.id.banner)
        mBannerLed = topHeader.findViewById(R.id.banner_led)
        mFlowViewZ = topHeader.findViewById(R.id.flow_view_z)
        mViewHSub = topHeader.findViewById(R.id.view_h_sub_company_home)
        mTvRZ = topHeader.findViewById(R.id.tv_rz_company_home)
        mIvGC = topHeader.findViewById(R.id.iv_gc_company_home)
        mIvPP = topHeader.findViewById(R.id.iv_pp_company_home)
        mViewLineGoods = topHeader.findViewById(R.id.view_line_goods)
        mViewLineRecome = topHeader.findViewById(R.id.view_line_recome)

        //        mTvDesExpend = topHeader.findViewById(R.id.tv_des_expend)
        mAdapter?.addHeaderView(topHeader)
        mTvAttention?.setOnClickListener(this@CompanyHomeFragment)
        mIvTel?.setOnClickListener(this@CompanyHomeFragment)
        mTvProduct?.setOnClickListener(this@CompanyHomeFragment)
        mTvRecome?.setOnClickListener(this@CompanyHomeFragment)

        mChangH = SizeUtils.dp2px(80.0f) + StatusBarUtil.getStatusBarHeight(requireContext())
//        mBinding?.clContainer?.alpha = 0.0f
//        mBinding?.rlTab?.alpha = 0.0f
//        mBinding?.ivShareWhite?.alpha = 1.0f
//        mBinding?.ivBackWhite?.alpha = 1.0f
        mIvWeiChat?.LoadSrc(Constants.KEY_WEIXIN_PIC)
    }

    private fun initAdapter() {

        mAddressAdapter = CompanyHomeAddressAdapter(mSiteBeans)
        mRvAddress?.adapter = mAddressAdapter
        mAddressAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            showMapSelected(data)
        }
        mGoodsUpAdapter = CompanyGoodsHorAdapter(mGoodsUPBeans)
        mRvUpGoods?.adapter = mGoodsUpAdapter
        mGoodsDownAdapter = CompanyGoodsHorAdapter(mGoodsDownBeans)
        mRvDownGoods?.adapter = mGoodsDownAdapter

        mGoodsUpAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            ARouter.getInstance().build(ARoutUtils.GoodsDetilsActivity).withString("spuid", data.id)
                .navigation()
        }
        mGoodsDownAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            ARouter.getInstance().build(ARoutUtils.GoodsDetilsActivity).withString("spuid", data.id)
                .navigation()
        }
        //禁止滑动  布局管理器
        val linearLayoutManager: LinearLayoutManager =
            object : LinearLayoutManager(requireContext()) {
                //禁止竖向滑动 RecyclerView 为垂直状态（VERTICAL）
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
        mRvRecomeGoods?.layoutManager = linearLayoutManager
        mRecomeGoodsAdapter = CompanyRecomeGoodsAdapter(mGoodsRecomeBeans)
        mRvRecomeGoods?.adapter = mRecomeGoodsAdapter
        mRvRecomeGoods?.addItemDecoration(
            SpacesItemDecoration(
                0, SizeUtils.dp2px(5.0f),
                false
            )
        )
        mRecomeGoodsAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            ARouter.getInstance().build(ARoutUtils.GoodsDetilsActivity).withString("spuid", data.id)
                .navigation()
        }



        mPhoneAdapter = RecyclerTextAdapter(mPhonesList)
        mRvPhone?.adapter = mPhoneAdapter
        mRvPhone?.addItemDecoration(
            SpacesItemDecoration(0, SizeUtils.dp2px(16.0f), false)
        )


    }

    override fun initData() {
        super.initData()
        arguments?.let {
            mCompanyInfo = it.getParcelable<CompanyItemBean>("companyBean")
        }
        UserDbHelper.getLiveUserInfo(requireContext()).observeKt {
            isLogin = !it?.id.isNullOrEmpty()
            mUserInfo = it
        }
        initUI()
        initAdapter()
        mCpLogo?.LoadSrc(mCompanyInfo?.image)
        mBinding?.ivLogo?.LoadSrc(mCompanyInfo?.image)
        mIvGC?.LoadSrc(Constants.FACTORY_TAG)
        mIvPP?.LoadSrc(Constants.BRAND_TAG)
//        mLLMini?.visibility =
//            if (mCompanyInfo?.wxappid.isNullOrEmpty()) View.GONE else View.VISIBLE
        mEwms.clear()
        val ewms = mCompanyInfo?.ewms
        ewms?.forEach { url ->
            mEwms.add(url.ewm ?: "")
        }
//        mLlWeiChat?.visibility =
//            if (ewms.isNullOrEmpty()) View.GONE else View.VISIBLE
        mCpyid = mCompanyInfo?.id ?: ""
        mTxaccid = mCompanyInfo?.txaccid ?: ""
        mCompanyCpName = mCompanyInfo?.name ?: ""
        findCompanyAccess()
        companyGoods()
        promoteGoods()
        mIsFoucs = mCompanyInfo?.status == "1"//0 未关注 1 关注
        mTvXinyong?.text = "信用分：${mCompanyInfo?.creditValue}"
        mTvCpname?.text = mCompanyCpName
        mBinding?.tvName?.text = mCompanyCpName
        mSiteBeans.clear()
        val site = mCompanyInfo?.site
        if (site.isNullOrEmpty()) {
            mAddress = mCompanyInfo?.prefecture ?: ""
            if (mAddress.isNotEmpty()) {
                mAddress =
                    "${mCompanyInfo?.province}${mCompanyInfo?.city}${mCompanyInfo?.area}${mCompanyInfo?.prefecture}${mCompanyInfo?.address}"
            } else {
                mAddress = "${mCompanyInfo?.address}"
            }
            mSiteBeans.add(AddressDetailsBean(mAddress, "", "", "", "", ""))
        } else {
            mSiteBeans.addAll(site)
        }
        mAddressAdapter?.notifyDataSetChanged()
        setFlowData()
        initPhones()

        //0  普通  1 银牌  2 金牌
        mSpecially = mCompanyInfo?.isspecially ?: "0"
        when (mSpecially) {
            "2" -> {
                mTvCpname?.setTextColor(Color.parseColor("#FFDC96"))
                mIvGold?.visibility = View.VISIBLE
                mTvGold?.visibility = View.VISIBLE
                mTvXinyong?.setTextColor(Color.parseColor("#999999"))
                mBinding?.clFloat?.setBackgroundColor(Color.parseColor("#262726"))
                mBinding?.ivTag?.visibility = View.VISIBLE
                mBinding?.tvName?.setTextColor(Color.parseColor("#FFDC96"))
                mBinding?.ivTag?.visibility = View.VISIBLE
            }

            else -> {
                mTvCpname?.setTextColor(Color.parseColor("#242424"))
                mIvGold?.visibility = View.GONE
                mTvGold?.visibility = View.GONE
                mTvXinyong?.setTextColor(Color.parseColor("#242424"))
                mBinding?.clFloat?.setBackgroundColor(Color.parseColor("#ffffff"))
                mBinding?.tvName?.setTextColor(Color.parseColor("#242424"))
                mBinding?.ivTag?.visibility = View.GONE
            }
        }
        val brand = mCompanyInfo?.brand ?: "0"
        val factory = mCompanyInfo?.factory ?: "0"
        mIvGC?.visibility = if (factory == "1") View.VISIBLE else View.GONE
        mIvPP?.visibility = if (brand == "1") View.VISIBLE else View.GONE
        mTvRZ?.visibility = if (mSpecially == "1") View.VISIBLE else View.GONE
        if (factory == "1" || brand == "1" || mSpecially == "1") {
            mViewHSub?.visibility = View.VISIBLE
        } else {
            mViewHSub?.visibility = View.GONE
        }
        initFoucs()
        val displayFac = mCompanyInfo?.displayFac
        displayFac?.let {
            var picCount = 0
            var videoCount = 0
            displayFac.indices.forEach { i ->
                val type = displayFac[i].type
                var mType = ViewTypeBean.PIC_TYPE
                if (type == "1") {
                    mType = ViewTypeBean.VEDIO_TYPE
                    videoCount++
                } else {
                    picCount++
                }
                mBannerBeans.add(ViewTypeBean(mType, displayFac[i]))
            }
            if (videoCount > 0) {
                mBanner?.isAutoLoop(false)
            } else {
                mBanner?.isAutoLoop(true)
                mBanner?.setLoopTime(1500)
            }
        }

        mBannerAdapter = BannerMediaNoBroderAdapter(mBannerBeans)
        mBanner?.adapter = mBannerAdapter
        mBanner?.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                if (mBannerBeans[position].type == ViewTypeBean.VEDIO_TYPE) {
                    startVideo(position)
                } else {
                    stopVideo()
                }
                inTentPosition = position

            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
//                ?.setOnBannerListener(OnBannerListener<ViewTypeBean> { data, position ->
//                    val json = GsonUtils.toJson(mBannerBeans)
//                    ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
//                        .withInt("position", position)
//                        .withString("data", json)
//                        .navigation()
//                })
        mBannerAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            inTentAction = true
//            var mP = position - 1
////            if (mBannerBeans[0].type == 1) {
////                mP = position
////            } else {
////                mP = position - 1
////            }
            val json = GsonUtils.toJson(mBannerBeans)
            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
                .withInt("position", position - 1)
                .withString("data", json)
                .navigation()
        }


    }


    private fun initPhones() {

        mPhones.clear()
        mPhonesList.clear()

        val contact = mCompanyInfo?.contact
        contact?.forEach {
            mPhones.add(CommonSelectedBean(it.tel, it.tel ?: ""))
            mPhonesList.add(CommonSelectedBean("联系方式：${it.name}  ${it.tel}"))
        }
        mPhoneAdapter?.notifyDataSetChanged()
    }

    private fun setFlowData() {
        mBnames.clear()
        val bnames = mCompanyInfo?.merito ?: ""
        val isJson = bnames.isJson()
        if (isJson) {
            val jsonType = object : TypeToken<List<String>>() {}.type
            val bnams: List<String> = GsonUtils.fromJson(bnames, jsonType)
            mBnames.addAll(bnams)
        } else {
            val tagDatas = bnames.split(",")
            tagDatas.forEach { tag ->
                mBnames.add(tag)
            }
        }


//        for (i in 0 until 37) {
//            var text = ""
//            if (i % 2 == 0) {
//                text = "数据$i"
//            } else {
//                text = "数据数据数据$i"
//            }
//            mBnames.add(text)
//        }
        mFlowViewZ?.setMinCount(3)
        mViewList.clear()
        for (i in 0 until mBnames.size) {
            val textChild = LayoutInflater.from(requireContext())
                .inflate(
                    R.layout.text_ec_tran_2_2, mFlowViewZ, false
                ) as TextView
            textChild.text = mBnames[i]
            textChild.setTextColor(Color.parseColor(if (mSpecially == "2") "#ffffff" else "#242424"))
            mViewList.add(textChild)
        }

        mFlowViewZ?.setChildren(mViewList)
        mFlowViewZ?.viewTreeObserver?.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mFlowViewZ?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                mLineCount = mFlowViewZ?.lineCount ?: 0 //行数
                mTwoLineViewCount = mFlowViewZ?.twoLineViewCount ?: 0 //前两行里面view的个数
                mExpandLineViewCount =
                    mFlowViewZ?.expandLineViewCount ?: 0///展开时显示view的个数
                if (mLineCount > minLines && !mExpend) {  //默认展示2行，其余折叠收起，最多展示5行
                    initIvClose(mTwoLineViewCount, mExpandLineViewCount);
                } else {
                    initIvOpen(mTwoLineViewCount, mExpandLineViewCount)
                }

            }
        })
    }

    private fun initIvClose(twoLineViewCount: Int, expandLineViewCount: Int) {
        mExpend = false
        mViewList.clear()
        for (i in 0 until twoLineViewCount) {
            val textView = LayoutInflater.from(requireContext())
                .inflate(
                    R.layout.text_ec_tran_2_2, mFlowViewZ, false
                ) as TextView
            textView.text = mBnames.get(i)
            textView.setTextColor(Color.parseColor(if (mSpecially == "2") "#ffffff" else "#242424"))
            mViewList.add(textView)
        }

        if (expandLineViewCount > twoLineViewCount) {
            //展开按钮
            val imageView = LayoutInflater.from(requireContext())
                .inflate(
                    R.layout.img_ec_2_2_tag, mFlowViewZ, false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_down)
            imageView.setOnClickListener { v: View? ->
                initIvOpen(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mViewList.add(imageView)
        }
        mFlowViewZ?.setChildren(mViewList)
//        mFlowViewZ?.viewTreeObserver
//            ?.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
//                override fun onGlobalLayout() {
//                    mFlowViewZ?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
//                    val lineCount: Int = mFlowViewZ?.lineCount ?: 0
//                    val twoLineViewCount: Int = mFlowViewZ?.twoLineViewCount ?: 0
//                    if (lineCount > minLines) {
//                        initIvClose(
//                            twoLineViewCount - 1,
//                            mFlowViewZ?.expandLineViewCount ?: 0
//                        )
//                    }
//                }
//            })
    }

    private fun initIvOpen(twoLineViewCount: Int, expandLineViewCount: Int) {
        mExpend = true
        mViewList.clear()
        for (i in 0 until expandLineViewCount) {
            val textView = LayoutInflater.from(requireContext())
                .inflate(
                    R.layout.text_ec_tran_2_2, mFlowViewZ, false
                ) as TextView
            textView.text = mBnames[i]
            textView.setTextColor(Color.parseColor(if (mSpecially == "2") "#ffffff" else "#242424"))
            mViewList.add(textView)
        }
        if (expandLineViewCount > twoLineViewCount) {
            //收起按钮
            val imageView = LayoutInflater.from(requireContext())
                .inflate(
                    R.layout.img_ec_2_2_tag, mFlowViewZ, false
                ) as ImageView
            imageView.setImageResource(com.lv.common.R.drawable.icon_arrow_up)
            imageView.setOnClickListener { v: View? ->
                initIvClose(
                    twoLineViewCount,
                    expandLineViewCount
                )
            }
            mViewList.add(imageView) //不需要的话可以不添加
        }
        mFlowViewZ?.setChildren(mViewList)
    }

    private var mVideo: YGXVideoTopPlayer? = null
    private fun startVideo(position: Int) {
        val vhMap = mBannerAdapter?.getVHMap()
        if (vhMap != null && vhMap.isNotEmpty() && vhMap.size > 0) {
            val viewHolder = vhMap.valueAt(0)
            if (viewHolder is BannerMediaNoBroderAdapter.BannerNoBorderMyViewVideoHolder) {
                mVideo = viewHolder.mVideo
                mVideo?.startPlayLogic()
            }
        }
    }

    private fun stopVideo() {
        if (mVideo == null) {
            if (mBannerBeans.size > 0 && mBannerBeans[0].type == ViewTypeBean.VEDIO_TYPE) {
                val get = mBannerAdapter?.getVHMap()?.valueAt(0)
                val viewHolder =
                    get as BannerMediaNoBroderAdapter.BannerNoBorderMyViewVideoHolder
                mVideo = viewHolder.mVideo
            }
        }
        mVideo?.onVideoPause()
    }

    /**
     * 轮播LED
     */
    private fun findCompanyAccess() {
        val accessMap = mutableMapOf<String, String>(
            "cpyid" to mCpyid
        )
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findCompanyAccess(accessMap) }.await()
            parseFindCompanyAccessResult(result)
        }
    }

    private fun parseFindCompanyAccessResult(
        data: DataResult<BaseYgxRsp>
    ) {
        data.onSuccess {
            onBizOK<LEDBeans> { code, data, message, result ->
//                val ledBeans = mutableListOf<String>()
                var leds = ""
                val mList = mutableListOf<String>()
                if (data.isNullOrEmpty()) {
                    mList.add("欢迎来到${mCompanyInfo?.name}")
                } else {

                    data.forEach { item ->
                        val time = TimeUtil.getDateTimeString(item.created, "HH:mm")
                        mList.add("${item.username}($time) 浏览")
                    }
                }
                val mLists = mutableListOf<String>()
                while (mLists.size < 10) {
                    mLists.addAll(mList)
                }
                mLists.forEach {
                    leds = "$leds    $it"
                }
                val mLedAdapter = CompanyLedAdapter(mList)
                mBannerLed?.adapter = mLedAdapter
                mBannerLed?.setOrientation(Banner.VERTICAL)
                    ?.setPageTransformer(ZoomOutPageTransformer())
                    ?.setIntercept(false)
            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
    }

    /**
     * 关注
     */
    private fun saveAttentionScope(body: CollectOrAttentionBody) {
//        (activity as BaseActivity<*>).startLoading()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.collectOrAttention(body) }.await()
            parseSaveAttentionResult(result)
        }
    }

    private fun parseSaveAttentionResult(
        data: DataResult<BaseYgxRsp>
    ) {
//        (activity as BaseActivity<*>).loadFinished()
        mTvAttention?.isEnabled = true
        data.onSuccess {
            onBizOK<String> { code, data, message, result ->
                var attentionnum = mCompanyInfo?.attentionnum ?: 0
                if (message == "取消关注") {
                    mIsFoucs = false
                    mCompanyInfo?.status = "0"
                    attentionnum -= 1
                } else {
                    mIsFoucs = true
                    mCompanyInfo?.status = "1"
                    attentionnum += 1
                }
                initFoucs()
//                LiveEventBus.get(CompanyEvent::class.java).post(CompanyEvent(mCompanyInfo))
                mCompanyInfo?.attentionnum = attentionnum
            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
    }

    /**
     * 企业产品
     */
    private fun companyGoods() {
        val attachedMap = mutableMapOf<String, String>(
            "cpyid" to mCpyid
        )
        (activity as BaseActivity<*>).startLoading()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.companyGoods(1, 24, attachedMap) }.await()
            parseCompanyGoodsResult(result)
        }
    }

    private fun parseCompanyGoodsResult(
        data: DataResult<BaseYgxRsp>
    ) {
        (activity as BaseActivity<*>).loadFinished()
        data.onSuccess {
            onBizOK<GoodsBean> { code, data, message, result ->
                data?.let {
                    val goods = data.items
                    mGoodsUPBeans.clear()
                    mGoodsDownBeans.clear()
                    mTvCompanyGoods?.text = "共${data.counts}个商品"
                    if (!goods.isNullOrEmpty()) {
                        val chunked = goods.chunked(4)
                        chunked.let {
                            for (i in chunked.indices) {
                                val companyInfoGoodsBeans = chunked[i]
                                if (!companyInfoGoodsBeans.isNullOrEmpty()) {
                                    when (i % 2) {
                                        0 -> mGoodsUPBeans.addAll(companyInfoGoodsBeans)
                                        else -> mGoodsDownBeans.addAll(companyInfoGoodsBeans)
                                    }
                                }
                            }
                        }
                        mGoodsUpAdapter?.notifyDataSetChanged()
                        mGoodsDownAdapter?.notifyDataSetChanged()
                    }
                    if (mGoodsDownBeans.isEmpty() && mGoodsUPBeans.isEmpty()) {
                        mCvCompanyGoods?.visibility = View.GONE
                    } else {
                        mCvCompanyGoods?.visibility = View.VISIBLE
                    }
                }
            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
    }

    /**
     * 主推产品
     */
    private fun promoteGoods() {
        val attachedMap = mutableMapOf<String, String>(
            "cpyid" to mCpyid
        )
        (activity as BaseActivity<*>).startLoading()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.promoteGoods(1, 24, attachedMap) }.await()
            parsePromoteGoodsResult(result)
        }
    }

    private fun parsePromoteGoodsResult(
        data: DataResult<BaseYgxRsp>
    ) {
        (activity as BaseActivity<*>).loadFinished()
        data.onSuccess {
            onBizOK<GoodsBean> { code, data, message, result ->
                data?.let {
                    mGoodsRecomeBeans.clear()
                    val goods = data.items
                    goods?.let { it1 -> mGoodsRecomeBeans.addAll(it1) }
                    mRecomeGoodsAdapter?.notifyDataSetChanged()
                    if (mGoodsRecomeBeans.isEmpty()) {
                        mCvRecome?.visibility = View.GONE
                    } else {
                        mCvRecome?.visibility = View.VISIBLE
                    }
                }
            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
    }

    private var mScrollY = 0
    private val changeScrollHeight = SizeUtils.dp2px(100.0f)
    override fun initEvents() {
        super.initEvents()
        mBinding?.rvContent?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mScrollY += dy
                val abss: Int = abs(mScrollY)
                var mAlpha = 0.0f
                if (abss > changeScrollHeight) {
                    mAlpha = (abss - changeScrollHeight) * 1.0f / changeScrollHeight
                    if (mAlpha > 1.0f) {
                        mAlpha = 1.0f
                    }
                    if (mAlpha < 0.0f) {
                        mAlpha = 0.0f
                    }
                }
                mBinding?.clFloat?.alpha = mAlpha

            }
        })
        rigestEventBus()
    }


    private fun rigestEventBus() {
//        LiveEventBus.get(CompanyEvent::class.java).observe(this) { event ->
//            if (event == null) {
//                return@observe
//            }
//            mCompanyInfo = event.companyItemBean
//            mIsFoucs = mCompanyInfo?.status == "1"//0 未关注 1 关注
//            initFoucs()

//        }

        //关注 点赞 评论 收藏
//        LiveEventBus.get(CirStatePageEvent::class.java).observe(this) { event ->
//            if (event == null) {
//                return@observe
//            }
//
//            when (event.tag) {
//                CirStateEventEnum.FOUCS -> {
//                    val cpyid = event.cpyid
//                    val id = mCompanyInfo?.id
//                    if (id == cpyid) {
//                        mIsFoucs = event.hasFocus == "1"
//                        initFoucs()
//                    }
//
//                }
//            }
//
//        }

    }

    private fun initFoucs() {
        mTvAttention?.text = if (mIsFoucs) "已关注" else "+ 关注"
        mBinding?.tvAttention?.text = if (mIsFoucs) "已关注" else "+ 关注"
        when (mSpecially) {
            "2" -> {
                if (mIsFoucs) {
                    mTvAttention?.setBackgroundResource(com.lv.common.R.drawable.bg_ff4242_10)
                    mBinding?.tvAttention?.setBackgroundResource(com.lv.common.R.drawable.bg_ff4242_10)
                    mTvAttention?.setTextColor(Color.parseColor("#ffffff"))
                    mBinding?.tvAttention?.setTextColor(Color.parseColor("#ffffff"))
                } else {
                    mTvAttention?.setBackgroundResource(com.lv.common.R.drawable.bg_line_ff4242_10)
                    mBinding?.tvAttention?.setBackgroundResource(com.lv.common.R.drawable.bg_line_ff4242_10)
                    mTvAttention?.setTextColor(Color.parseColor("#ff4242"))
                    mBinding?.tvAttention?.setTextColor(Color.parseColor("#ff4242"))
                }
            }

            else -> {
                if (mIsFoucs) {
                    mTvAttention?.setBackgroundResource(com.lv.common.R.drawable.bg_theme_10)
                    mBinding?.tvAttention?.setBackgroundResource(com.lv.common.R.drawable.bg_theme_10)
                    mTvAttention?.setTextColor(Color.parseColor("#ffffff"))
                    mBinding?.tvAttention?.setTextColor(Color.parseColor("#ffffff"))
                } else {
                    mTvAttention?.setBackgroundResource(com.lv.common.R.drawable.bg_line_theme_10)
                    mBinding?.tvAttention?.setBackgroundResource(com.lv.common.R.drawable.bg_line_theme_10)
                    mTvAttention?.setTextColor(Color.parseColor("#026DFF"))
                    mBinding?.tvAttention?.setTextColor(Color.parseColor("#026DFF"))
                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back_black, R.id.iv_back_white -> {
                activity?.finish()
            }

            R.id.iv_share_white, R.id.iv_share_black -> {
                if (mCpyid.isNotEmpty()) {
//                    YgxManager.showDialogShare(
//                        requireActivity(),
//                        mCompanyInfo?.name ?: "",
//                        mCompanyInfo?.caption ?: "这个用户很懒，什么都没有留下~",
//                        "${Constants.KEY_SHARE_HEADER_SYY}${Constants.KEY_SHARE_COMPANY}${mCompanyInfo?.id}${Constants.KEY_SHARE_COMPANY_PRO}$mForshort",
//                        Constants.KEY_SHARE_COMPANY_CASH_WEIXIN + mCpyid + "_" + mForshort + Constants.KEY_SHARE_COMPANY_CASH_WEIXIN_END,
//                        mCompanyInfo?.logo ?: "", -1, OnPositionListener {
//                            LiveEventBus.get(CompanyShareEvent::class.java)
//                                .post(CompanyShareEvent())
//                        }
//                    )
                }
            }

            R.id.tv_attention -> {
                //登录
                lifecycleScope.launch {
                    if (isLogin) {
                        mTvAttention?.isEnabled = false
                        saveAttentionScope(CollectOrAttentionBody("1", mCpyid))
                    } else {
                        ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
                    }
                }
            }

//            R.id.iv_location -> {
//                showMapSelected()
//            }

            R.id.iv_tel -> showPhonePopSelected()
            R.id.tv_info_more -> {
//                ARouter.getInstance().build(ARoutUtils.CompanyInfoShowActivity)
//                    .withParcelable("companyinfo", mCompanyInfo)
//                    .navigation()
                if (isLogin) {
                    UserUtils.showChatActivity(mTxaccid, mCompanyCpName)
                } else {
                    ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
                }
            }

            R.id.tv_des -> {
                if (mShowCompanyDecPop) {
                    showInterDuceDialog()
                }
            }

            R.id.iv_code -> showCodeDialog()
            R.id.tv_produce -> {
                (requireActivity() as CompanyInfoActivity).setTabSelected(1)
                LiveEventBus.get(TabPageEvent::class.java)
                    .post(TabPageEvent("CompanyCategoryTabFragment", 0))
            }

            R.id.tv_recome -> {
                (requireActivity() as CompanyInfoActivity).setTabSelected(1)
                LiveEventBus.get(TabPageEvent::class.java)
                    .postDelay(TabPageEvent("CompanyCategoryTabFragment", 2), 500)
            }

//            R.id.ll_search -> ARouter.getInstance().build(ARoutUtils.CompanySearchActivity)
//                .withString("cpyid", mCpyid)
//                .navigation()


//            R.id.ll_wei_chat -> YgxPickerUtilsKt.showEwmCode(requireContext(), mEwms)
        }
    }


    private fun showInterDuceDialog() {
        val popupView =
            ShowCenterTextPopupView(requireContext(), "企业简介", mCompanyInfo?.caption ?: "")
        XPopup.Builder(requireContext())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .asCustom(popupView)
            .show()
    }

    //二维码展示
    private fun showCodeDialog() {
        val url = ""
//            "${Constants.KEY_SHARE_HEADER_SYY}${Constants.KEY_SHARE_COMPANY}${mCompanyInfo?.id}${Constants.KEY_SHARE_COMPANY_PRO}$mForshort"
        val popupView =
            ShowCodeBorderPopupView(
                requireContext(), url, mCompanyInfo?.image ?: ""
            )
        XPopup.Builder(requireContext())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .asCustom(popupView)
            .show()
    }

    private fun showMapSelected(address: String) {
        val mPopupView =
            ListSingleTextTagPopupView(
                requireContext(), mAddressBeans,
            ) { current, data ->
                if (current != -1) {
//                    mAddress="湖北省武汉市长江大桥"
                    when (current) {
                        0 -> {
                            val installed = MyUtils.isInstalled("com.tencent.map")
                            if (installed) {
                                val i1 = Intent()
                                //调起腾讯地图APP，在上海搜索美食
                                i1.data =
                                    Uri.parse("qqmap://map/search?keyword=$address&referer=速易甬")
                                startActivity(i1)
                            } else {
                                showToast("请安装腾讯地图")
                            }
                        }

                        1 -> {
                            val installed = MyUtils.isInstalled("com.autonavi.minimap")
                            if (installed) {
                                val intent = Intent()
                                intent.action = Intent.ACTION_VIEW
                                intent.addCategory(Intent.CATEGORY_DEFAULT)
                                //将功能Scheme以URI的方式传入data
                                val uri =
                                    Uri.parse("androidamap://poi?sourceApplication=速易甬&keywords=$address")
                                intent.data = uri
                                //启动该页面即可
                                startActivity(intent)
                            } else {
                                showToast("请安装高德地图")
                            }
                        }

                        2 -> {
                            val installed = MyUtils.isInstalled("com.baidu.BaiduMap")
                            if (installed) {
                                val i1 = Intent()
                                // 驾车导航
                                i1.data = Uri.parse("baidumap://map/navi?query=$address")
                                startActivity(i1)
                            } else {
                                showToast("请安装百度地图")
                            }
                        }
                    }
                }
            }


        XPopup.Builder(requireContext())
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()

    }

    private var mPhones = mutableListOf<CommonSelectedBean>()

    private fun showPhonePopSelected() {
        if (mPhones.size == 1) {
            mPhone = mPhones[0].tag ?: ""
            YgxUtilsKt.callPhone(requireContext(), mPhone)
            sendCallMessage()
            return
        }
        val mPopupView =
            ListSingleTextPopupView(
                requireContext(), mPhones
            ) { current, data ->
                if (current != -1) {
                    mPhone = data.tag ?: ""
                    YgxUtilsKt.callPhone(requireContext(), mPhone)
                    sendCallMessage()
                    savecallnum()
                }

            }

        XPopup.Builder(requireContext())
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()
    }

    private fun sendCallMessage() {
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { serviceViewModel.sendCallMessage(mPhone) }.await()
//        }
    }

    private fun savecallnum() {
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { serviceViewModel.savecallnum(mCompanyInfo?.id ?: "") }.await()
//
//        }
    }


    override fun onResume() {
        super.onResume()
        LogUtils.e("aaaaaaaaaaaaaaaaaa--onResume")
        if (inTentAction) {
            if (mBannerBeans.isNotEmpty() && mBannerAdapter != null && mBannerBeans[inTentPosition].type == ViewTypeBean.VEDIO_TYPE) {
                startVideo(inTentPosition)
            }
            inTentAction = false
        }
    }

    override fun onPause() {
        super.onPause()
        mVideo?.onVideoPause()
        inTentAction = true
    }

    override fun onDestroy() {
        super.onDestroy()
        mVideo?.release()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK || data == null) {
            return
        }
        val isFoucs = data.getBooleanExtra("state", false)
        var attentionnum = mCompanyInfo?.attentionnum ?: 0
        if (mIsFoucs) {
            if (!isFoucs) {//取消关注
                attentionnum -= 1
                mCompanyInfo?.attentionnum = attentionnum
            }
        } else {
            if (isFoucs) {//关注
                attentionnum += 1
                mCompanyInfo?.attentionnum = attentionnum
            }
        }
        mIsFoucs = isFoucs
        mCompanyInfo?.status = if (isFoucs) "1" else "0"
        initFoucs()
    }

    companion object {
        fun newInstance(companyBean: CompanyItemBean?): CompanyHomeFragment {
            val args = Bundle()
            args.putParcelable("companyBean", companyBean)

            val fragment = CompanyHomeFragment()
            fragment.arguments = args
            return fragment
        }
    }

}